package com.ruoyi.framework.web.exception;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.apache.catalina.connector.ClientAbortException;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * 全局异常处理器
 * 
 * @author ruoyi
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 文件上传异常
     */
    @ExceptionHandler(MultipartException.class)
    public AjaxResult handleMultipartException(MultipartException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}'发生文件上传异常", requestUri, e);
        
        Throwable cause = e.getCause();
        if (cause != null && cause.getCause() instanceof java.io.EOFException) {
            return AjaxResult.error("文件上传中断，请重新上传或检查网络连接");
        }
        
        return AjaxResult.error("文件上传失败，请稍后重试");
    }
    
    /**
     * 客户端中断异常
     */
    @ExceptionHandler(ClientAbortException.class)
    public AjaxResult handleClientAbortException(ClientAbortException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}'客户端中断异常", requestUri, e);
        return AjaxResult.error("客户端中断了请求");
    }
    
    /**
     * 文件大小超出限制异常
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public AjaxResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e, HttpServletRequest request) {
        String requestUri = request.getRequestURI();
        log.error("请求地址'{}'文件大小超出限制", requestUri, e);
        return AjaxResult.error("文件大小超出限制，请压缩后重新上传");
    }
}